//
//  LBWStatusPictureView.swift
//  weibo
//
//  Created by Limonwei on 15/12/11.
//  Copyright © 2015年 heima. All rights reserved.
//

//抽象微博配图的视图 继承UICollectionView

import UIKit
import SnapKit

//重用标示符
private let LBWStatusPictureViewItemId = "LBWStatusPictureViewItemId"

//每一个条目 cell之间的小间距
private let itemMargin: CGFloat = 5

//每一个条目的宽高
private let itemWH = (SCREENW - itemMargin * 2 - LBWStatusCellMargin * 2)/3

class LBWStatusPictureView: UICollectionView {
    
    var sizeConstraint: Constraint?
    
    //当前配图视图显示的图片数据
    
    var pic_urls: [LBWStatusPictureInfo]? {
        
        didSet{
            
            //countLabel.text = "\(pic_urls?.count ?? 0)"
            
            //根据图片张数,计算当前控件的大小
            let size = calcSize(pic_urls?.count ?? 0)
            
            self.snp_updateConstraints { (make) -> Void in
                self.sizeConstraint = make.size.equalTo(size).constraint
            }
            
            
            //刷新数据
            reloadData()
        }
    }
    
    //设置collectionViewLayout
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setupUI()
        
        //设置collectionView相关属性
        //注册cell
        registerClass(LBWStatusPictureViewCell.self, forCellWithReuseIdentifier: LBWStatusPictureViewItemId)
        
        //设置数据源 以及代理
        dataSource = self
        delegate = self
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        //设置条目的大小
        
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        
        //指定水平方向的间距
        layout.minimumInteritemSpacing = itemMargin
        
        //指定垂直方向的间距
        layout.minimumLineSpacing = itemMargin
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //设置视图
    private func setupUI(){
//        addSubview(countLabel)
//        
//        //设置约束
//        countLabel.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(self)
//        }
        
    }
    
    //计算当前控件的大小
    
    private func calcSize(count: Int) ->CGSize {
        
        //计算当前显示的行数与列数
        //列数
        let col = count == 4 ? 2 : (count >= 3 ? 3 : count)
        //行数
        let row = count == 4 ? 2 : ((count - 1)/3 + 1)
        
        //计算当前控件的宽高 
        //宽度 = 列数*每一个条目的宽度 + (列数减1)*条目之前的间距
        let width = CGFloat(col) * itemWH + CGFloat(col) * itemMargin
         //高度 = 行数*每一个条目的宽度 + (行数减1)*条目之前的间距
         let height = CGFloat(row) * itemWH + CGFloat(row) * itemMargin
        
        return CGSize(width: width, height: height)
    }
    
//    //懒加载一个label记录图片张数
//    private lazy var countLabel: UILabel = UILabel(textColor: UIColor.redColor(), fontSize: 40)

}

//设置UICollectionViewDataSource 数据源方法
extension LBWStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    //必须实现的两个方法
    
    //返回有多少个cell
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pic_urls?.count ?? 0
    }

    
    //返回怎样的cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        //强转一下cell为自定的就ok
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LBWStatusPictureViewItemId, forIndexPath: indexPath) as! LBWStatusPictureViewCell
        
        cell.pictureInfo = pic_urls![indexPath.row]
        
        return cell
    }
    
    //点击每张图片可以查看
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
        //browser.sourceImagesContainerView = self; // 原图的父控件
        //browser.imageCount = self.photoItemArray.count; // 图片总数
        //browser.currentImageIndex = button.tag;
        //browser.delegate = self;
        //[browser show];
        
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        // 图片张数
        browser.imageCount = pic_urls?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
    }

}

//第三方图片浏览器配置

extension LBWStatusPictureView: SDPhotoBrowserDelegate {
    // 返回对应 index 的图片 --> 在我们这种情况下,是返回 对应 item 的 cell 里面的图片
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        //设置indexPath
        let index = NSIndexPath(forItem: index, inSection: 0)
        //通过indexPath获取到其对应的cell
        if let cell = self.cellForItemAtIndexPath(index) as? LBWStatusPictureViewCell {
            return cell.imageView.image
        }
        return nil
        
    }
    
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlString = pic_urls![index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        
        return NSURL(string: urlString)
        
    }
}


//自定义collectionView的cell
class LBWStatusPictureViewCell: UICollectionViewCell {
    
    var pictureInfo: LBWStatusPictureInfo? {
        
        //外界在给pictureInfo设置完值后会调用didSet方法
        didSet{
            
            if let urlString = pictureInfo?.thumbnail_pic {
                
                //设置GIF标识
                GifImage.hidden = !urlString.hasSuffix(".gif")
                
                //下载配图
                imageView.sd_setImageWithURL(NSURL(string: urlString), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                
            }
            
        }
        
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置UI视图
    private func setupUI(){
        
        //backgroundColor = RandomColor()
        //添加控件
        contentView.addSubview(imageView)
        contentView.addSubview(GifImage)
        
        
        //添加约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        GifImage.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(imageView)
            make.bottom.equalTo(imageView)
        }
        
    }
    
    //懒加载控件
    
    //图片
    private lazy var imageView: UIImageView = {
        
        let imageView = UIImageView()
        
        
        //指定内容显示的模式
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        
        //裁掉超出部分
        imageView.clipsToBounds = true
        
        
        return imageView

    }()
    
    //gif图标
    private lazy var GifImage: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
}
























